package com.ktjiaoyu.crm.config.shiro;

import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("调用doGetAuthorizationInfo()获取权限信息..........");
        //获取权限信息
        User user = (User)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用doGetAuthenticationInfo()获取身份信息..........");
        //获取身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //获取token中的用户名
        String username = token.getUsername();
        //根据用户名调用用户信息
        User user = userService.getUesrByName(username);
        if(user == null) throw new UnknownAccountException();   //账号错误
        if(user.getUsrFlag()==null || user.getUsrFlag().intValue()==0) throw new LockedAccountException(); //账号被锁定
        //principal：身份
        //credentials：凭证
        //realmName：当前Realm的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUsrPassword(),getName());

        return info;
    }
}
